﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TableProto;
using WCBG.ToolsForUnity.Tools;
using WCBG.ToolsForUnity.Extension;
using DG.Tweening;

/// <summary>
/// 英语颜色 找房子
/// </summary>
public class FindHouseGameWindow : SingletonBaseWindow<FindHouseGameWindow>
{

    #region ui property

    public Button _Btn_Return { get; set; }
    public Button _Btn_LoudSpeaker { get; set; }
    public RectTransform _HouseGroup { get; set; }
    public RectTransform _bslStartPoint { get; set; }
    public RectTransform _bslEndPoint { get; set; }


    #endregion

    private const string TEXTURE_BASE_PATH = EnglishColoursPath.englishColorLetterTexturePath;
    private const float HINT_INTERVAL_TIM = 15f;

    private RectTransform m_createBsl;
    private GameAudioSource m_curAudio;

    private bool isLockInput;
    private bool isMoving;
    private int hintSeq;
    private int m_levelIndex;

    private EnglishColoursInfo[] m_infoArr;
    private EnglishColoursInfo m_levelInfo;


    private System.Action<int, System.Action> levelCallback;
    private System.Action<bool> allLevelCallback;

    private List<FindHouseHolder> m_holderList = new List<FindHouseHolder>();
    private List<int> m_levelList = new List<int>();

    protected override void OnOpen(params object[] paramArray)
    {
        _bslStartPoint.SetActive(false);
        _bslEndPoint.SetActive(false);

        InitGame();
    }

    protected override void OnClose()
    {
        if (m_createBsl != null)
        {
            GameObject.Destroy(m_createBsl.gameObject);
            m_createBsl = null;
        }
    }

    protected override void AddListeners()
    {
        _Btn_Return.onClick.AddListener(OnButtonReturnClick);
        _Btn_LoudSpeaker.onClick.AddListener(OnBtn_LoudSpeakerClick);
    }

    protected override void RemoveListensers()
    {
        _Btn_Return.onClick.RemoveAllListeners();
        _Btn_LoudSpeaker.onClick.RemoveAllListeners();
    }


    

    private void InitGame()
    {
        m_holderList.Clear();
        for (int i = 0; i < _HouseGroup.childCount; i++)
        {
            FindHouseHolder holder = _HouseGroup.GetChild(i).AddComponentEx<FindHouseHolder>();
            m_holderList.Add(holder);
        }

        if (m_createBsl == null)
        {
            m_createBsl = GameObject.Instantiate(_bslStartPoint.gameObject, _bslStartPoint.parent).GetComponent<RectTransform>();
            m_createBsl.position = _bslStartPoint.position;
            m_createBsl.gameObject.SetActive(false);

        }
        _HouseGroup.SetActive(false);
    }

    private void StartGame(EnglishColoursInfo[] infoArr)
    {
        _HouseGroup.SetActive(true);
        m_levelIndex = 0;
        m_levelList.Clear();
        for (int i = 0; i < m_holderList.Count; i++)
        {
            EnglishColoursInfo info = infoArr[i];
            FindHouseHolder holder = m_holderList[i];
            if (info != null)
            {
                string[] arr = info.mainTex.Split(';');
                holder.Initialize(info.word, arr[0], arr[1], info.SpecialColor.ConvertToColor(), OnHolderClick);
                holder.ScaleIn();
                m_levelList.Add(i);
            }
            else
            {
                holder.gameObject.SetActive(false);
            }
        }
        this.PlayAudioEx(StudyAudioName.t_41009);

        StartLevel();
    }

    private void StartLevel()
    {
        isMoving = true;
        m_createBsl.SetActive(true);
        m_createBsl.localScale = Vector3.one;
        m_createBsl.position = _bslStartPoint.position;
        m_createBsl.DOMove(_bslEndPoint.position, 0.5f).SetEase(Ease.Linear);

        if (hintSeq >= 0)
        {
            this.RemoveTimerEx(hintSeq);
        }

        this.AddTimerEx(0.5f, () =>
        {
            isMoving = false;

            if (m_levelList.Count == 0)
            {
                OnGameComplete();
                return;
            }

            int rd = Random.Range(0, m_levelList.Count);
            m_levelInfo = m_infoArr[m_levelList[rd]];
            m_levelList.RemoveAt(rd);
            hintSeq = this.AddTimerEx(HINT_INTERVAL_TIM, true, OnAudioHint);
            OnAudioHint(0);
        });

    }

    private void OnLevelComplete()
    {
        if (m_levelList.Count == 0)
        {
            OnGameComplete();
        }
        else
        {
            if (levelCallback != null)
            {
                levelCallback(m_levelIndex, () =>
                {
                    isMoving = false;
                    m_levelIndex++;
                    StartLevel();
                });
            }
        }
    }

    private void OnAudioHint(int seq)
    {
        if (isMoving)
            return;
        if (m_curAudio != null)
            return;
        m_curAudio = this.PlayEnglishColoursAudioEx(m_levelInfo.wordAudio);
        this.AddTimerEx(m_curAudio.Length, () => {
            m_curAudio = null;
        });
        Debug.LogError("--------------------  on hit:" + m_levelInfo.word);
    }

    private void OnHolderClick(FindHouseHolder holder)
    {
        if (isMoving)
            return;
        if (!holder.isComplete)
        {
            isMoving = true;
            
            GameAudioSource audio = this.PlayAudioEx(StudyAudioName.t_41010);
            (this).AddTimerEx(audio.Length + 0.2f, () =>
            {
                float maxDis = Vector3.Distance(_bslEndPoint.position, m_holderList[0].doorPos);
                float time = Vector3.Distance(holder.doorPos, m_createBsl.position) / maxDis * 3f;

                if (m_levelInfo.word == holder.word)
                {
                    Debug.LogError("--------------------  OnSelectTure");
                    m_createBsl.DOMove(holder.doorPos, time).SetEase(Ease.Linear);
                    GameAudioSource audio1 = (this).PlayAudioEx(StudyAudioName.t_41011, true);
                    (this).AddTimerEx(time, () =>
                    {
                        audio1.Stop();

                        (this).RemoveTimerEx(hintSeq);

                        GameAudioSource audio2 = (this).PlayAudioEx(StudyAudioName.t_41012);
                        (this).AddTimerEx(audio2.Length + 0.5f, () =>
                        {
                            GameAudioSource audio3 = (this).PlayAudioEx(StudyAudioName.t_42001);
                            (this).AddTimerEx(audio3.Length + 0.5f, () =>
                            {
                                float time1 = 0.5f;
                                m_createBsl.DOScale(0, time1).SetEase(Ease.Linear);
                                (this).AddTimerEx(time1 + 1f, () =>
                                {
                                    holder.PlayCompleteAnim(OnLevelComplete);
                                });
                            });
                        });

                    });
                }
                else
                {
                    Debug.LogError("--------------------  OnSelectFalse");
                    BslActor bslActor = m_createBsl.GetComponent<BslActor>();
                    bslActor.ChangeState(BslActor.State.cuowu);
                    GameAudioSource audio2 = (this).PlayAudioEx(StudyAudioName.t_41013);
                    (this).AddTimerEx(audio2.Length + 0.5f, () =>
                    {
                        GameAudioSource audio3 = (this).PlayAudioEx(StudyAudioName.t_42002);
                        (this).AddTimerEx(audio3.Length, () => {
                            isMoving = false;
                            bslActor.ChangeState(BslActor.State.idle);
                        });
                    });

                }

               
            });
        }
    }

    private void OnGameComplete()
    {
        if (allLevelCallback != null)
        {
            allLevelCallback(true);
        }
    }



    #region uievent

    private void OnButtonReturnClick()
    {
        if (isLockInput)
            return;
        isLockInput = true;

        //if (allLevelCallback != null)
        //{
        //    allLevelCallback(false);
        //}
        EnglishColorManager.Instance.StopCurrentGame();
    }

    private void OnBtn_LoudSpeakerClick()
    {
        if (m_curAudio == null)
        {
            m_curAudio = this.PlayEnglishColoursAudioEx(m_levelInfo.wordAudio);
            this.AddTimerEx(m_curAudio.Length, () =>
            {
                m_curAudio = null;
            });
        }
    }

    #endregion



    public void StartGame(EnglishColoursInfo[] infoArr, System.Action<int, System.Action> levelCallback, System.Action<bool> allLevelCallback)
    {
        if (infoArr == null)
        {
            Debug.LogError("Fill info is null!");
            if (allLevelCallback != null)
                allLevelCallback(false);
            return;
        }

        m_infoArr = infoArr;
        this.levelCallback = levelCallback;
        this.allLevelCallback = allLevelCallback;
        isLockInput = false;

        this.AddTimerEx(1.5f, ()=>
        {
            StartGame(infoArr);
        });
    }

    private Sprite LoadSprite(string name)
    {
        return Res.LoadSprite(TEXTURE_BASE_PATH + name);
    }

    private void ClearLetter()
    {

    }


}
